import React, { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { Input, Button, Table, message, Modal, Select } from "antd";
import {
  PlusOutlined,
  BlockOutlined,
  AccountBookOutlined,
  SearchOutlined,
} from "@ant-design/icons";
import { text_check, post_axios } from "../../utils";

export default function CompanyManager(props) {
  const { t } = useTranslation();
  const { actions, setSpinning } = props;
  let { menu_action, user_power_lang, username } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const localStorage_company_obj =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";
  const local_company_string =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]["company"]
      ? localStorage_company[username]["company"]
      : "";

  const [company_str, setCompany_str] = useState("");
  const [tableHeight, setTableHeight] = useState(0);

  const [page, setPage] = useState(1);
  const [rows, setRows] = useState(20);
  const [company_list, setCompany_list] = useState([]);
  const [total, setTotal] = useState(0);
  // 获取公司列表
  const getData = async (newPage, newRows) => {
    let upMsg = {
      company: company_str,
      page: newPage ? newPage : page,
      rows: newRows ? newRows : rows,
    };
    setSpinning(true);
    let res = await post_axios("company_manager", "m_query", upMsg);
    setSpinning(false);
    setCompany_list(res.data_rows.rows);
    setTotal(res.data_rows.total);
  };

  const columns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("platform_manager.company_name"),
      dataIndex: "company",
      align: "center",
    },
    {
      title: t("platform_manager.pinyin"),
      dataIndex: "pinyin",
      align: "center",
    },
    {
      title: t("platform_manager.Initials"),
      dataIndex: "firstLetter",
      align: "center",
    },
    {
      title: "id",
      dataIndex: "id",
      align: "center",
    },
    {
      title: t("platform_manager.select_company"),
      dataIndex: "",
      align: "center",
      width: 200,
      render: (_, record) => (
        <Button
          size="small"
          type="primary"
          onClick={() => choose_company_btn_func(record)}
        >
          {t("common.select")}
        </Button>
      ),
    },
  ];
  // 分页器
  const pageOnChange = async (page, pageSize) => {
    setPage(page);
    setRows(pageSize);
    initData(page, pageSize);
  };

  const search_data = () => {
    setPage(1);
    initData(1);
  };

  const initData = (page, rows) => {
    setClick_company("");
    setClicked_company_obj({});
    getData(page, rows);
  };

  // 公司数据行点击
  const [clicked_company, setClick_company] = useState("");
  const [clicked_company_obj, setClicked_company_obj] = useState({});

  const company_row_click = (row) => {
    console.log(row);
    setClick_company(row.id);
    setClicked_company_obj(row);
  };

  // 点击选择公司
  const choose_company_btn_func = (value) => {
    localStorage.setItem(
      "choose_company",
      JSON.stringify({
        [username]: value,
      })
    );
    window.location.reload();
  };

  const [addCompanyShow, setAddCompanyShow] = useState(false);
  const [addCompanyStr, setAddCompanyStr] = useState("");
  const add_company = () => {
    setAddCompanyStr("");
    setAddCompanyShow(true);
  };
  const addCompanyConfirm = async () => {
    let upMsg = {
      company: addCompanyStr,
    };
    setSpinning(true);
    let res = await post_axios("company_manager", "m_add", upMsg);
    setSpinning(false);
    if (!res) return;
    message.success({
      content: t("common.add_scuuess"),
    });
    setAddCompanyShow(false);
    search_data();
  };

  const [bind_box_type_name, setBind_box_type_name] = useState([]);
  const [bind_box_type_show, setBind_box_type_show] = useState(false);
  const [box_type_list, setBox_type_list] = useState([]);
  // 查询货柜
  const get_box_type_data = async () => {
    let upMsg = {};
    let res = await post_axios("company_manager", "m_query_box_type", upMsg);
    if (!res) return;
    let rows = res.data_rows.rows.map((item) => {
      return {
        key: item.box_type_id,
        label: item.box_type_name,
        value: item.box_type_id,
      };
    });
    setBox_type_list(rows);
  }; // 绑定货柜
  const bind_box_type = async () => {
    if (clicked_company === "") {
      message.warning({
        content: t("platform_manager.select_a_company"),
      });
      return;
    }
    let upMsg = {
      company_id: localStorage_company_obj.id,
    };
    let res = await post_axios("company_manager", "m_query_box_type", upMsg);
    let names = res.data_rows.rows.map((item) => {
      return item.box_type_id;
    });
    setBind_box_type_name(names);
    setBind_box_type_show(true);
  };
  const bind_box_type_change = (value, array) => {
    console.log(value, array);
    setBind_box_type_name(value);
  };
  // 提交绑定的货柜
  const bind_box_type_confirm = async () => {
    if (bind_box_type_name.length == 0) {
      message.warning({
        content: t("platform_manager.select_a_box"),
      });
      return;
    }
    setSpinning(true);
    let upMsg = {
      company_id: localStorage_company_obj.id,
      name: bind_box_type_name,
    };
    let res = await post_axios("company_manager", "m_set_box_type", upMsg);
    setSpinning(false);
    if (!res) return;
    message.success({
      content: t("common.success"),
    });
    setBind_box_type_show(false);
  };

  const [pay_type_list, setPay_type_list] = useState([]);
  const [bind_pay_type_show, setBind_pay_type_show] = useState(false);
  const [bind_pay_type_name, setBind_pay_type_name] = useState([]);
  // 查询支付方式
  const get_pay_type_data = async () => {
    let upMsg = {};
    let res = await post_axios("company_manager", "m_query_pay_type", upMsg);
    let rows = res.data_rows.rows.map((item) => {
      return {
        label: text_check(item),
        value: item.flag,
        key: item.flag,
      };
    });
    setPay_type_list(rows);
  };
  // 绑定支付方式
  const bind_pay_type = async () => {
    if (clicked_company === "") {
      message.warning({
        content: t("platform_manager.select_a_company"),
      });
      return;
    }
    let upMsg = {
      company_id: localStorage_company_obj.id,
    };
    let res = await post_axios("company_manager", "m_query_pay_type", upMsg);
    let names = res.data_rows.rows.map((item) => {
      return item.flag;
    });
    setBind_pay_type_name(names);
    setBind_pay_type_show(true);
  };

  const bind_pay_type_change = (value, array) => {
    console.log(value, array);
    setBind_pay_type_name(value);
  };
  // 提交绑定支付方式
  const bind_pay_type_confirm = async () => {
    if (bind_pay_type_name.length == 0) {
      message.warning({
        content: t("platform_manager.select_a_pay_type"),
      });
      return;
    }
    let upMsg = {
      company_id: localStorage_company_obj.id,
      name: [...bind_pay_type_name],
    };
    setSpinning(true);
    let res = await post_axios("company_manager", "m_set_pay_type", upMsg);
    setSpinning(false);
    if (!res) return;
    message.success({
      content: t("common.success"),
    });
    setBind_pay_type_show(false);
  };

  useEffect(() => {
    // 挂载后或者更新后的操作
    getData().then(() => {
      const tabHeight =
        document.getElementsByClassName("company_manager")[0].scrollHeight;
      const Y = tabHeight - 96 - 70;
      setTableHeight(Y);
    });
    get_box_type_data();
    get_pay_type_data();
  }, []);
  return (
    <>
      <div className="company_manager modules">
        <div className="screen_ipt">
          <div className="ipt_box">
            <div className="ipt_box_title">
              {t("platform_manager.company_name")}
            </div>
            <Input
              value={company_str}
              type="text"
              onChange={(e) => setCompany_str(e.target.value)}
              size="small"
              allowClear
            />
          </div>
        </div>

        <div className="screen_btn">
          <div className="btn_box">
            {/* 添加 */}
            {menu_action.indexOf("m_add") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<PlusOutlined style={{ color: "#1677FF" }} />}
                onClick={add_company}
              >
                {text_check(user_power_lang["m_add"])}
              </Button>
            ) : (
              ""
            )}
            {/* 绑定货柜 */}
            {menu_action.indexOf("m_set_box_type") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<BlockOutlined style={{ color: "#1677FF" }} />}
                onClick={bind_box_type}
              >
                {text_check(user_power_lang["m_set_box_type"])}
              </Button>
            ) : (
              ""
            )}
            {/* 绑定支付方式 */}
            {menu_action.indexOf("m_set_pay_type") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<AccountBookOutlined style={{ color: "#1677FF" }} />}
                onClick={bind_pay_type}
              >
                {text_check(user_power_lang["m_set_pay_type"])}
              </Button>
            ) : (
              ""
            )}
            {/* 查询 */}
            {menu_action.indexOf("m_query") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<SearchOutlined style={{ color: "#1677FF" }} />}
                onClick={search_data}
              >
                {text_check(user_power_lang["m_query"])}
              </Button>
            ) : (
              ""
            )}
          </div>
          {local_company_string !== "" ? (
            <div className="choosed_company">
              {t("platform_manager.selected_company")}：{local_company_string}
            </div>
          ) : (
            ""
          )}
        </div>

        <div className="table_box">
          <div
            className="page-table"
            style={{
              width: "100vw",
            }}
          >
            <Table
              dataSource={company_list}
              size="small"
              bordered
              columns={columns}
              rowKey="id"
              virtual
              rowHoverable={false}
              scroll={{
                y: tableHeight,
              }}
              onRow={(record) => {
                return {
                  onClick: () => company_row_click(record), // 点击行
                };
              }}
              rowClassName={(record, index) => {
                if (record.id == clicked_company) {
                  return "row_clicked_style";
                }
              }}
              pagination={{
                defaultCurrent: page,
                defaultPageSize: rows,
                size: "small",
                current: page,
                total: total,
                responsive: true,
                showTotal: (total) =>
                  text_check({
                    msg_cn: `共 ${total} 条`,
                    msg_en: `Total ${total} items`,
                  }),
                onChange: pageOnChange,
              }}
            />
          </div>
        </div>
      </div>

      <Modal
        title={t("common.add")}
        open={addCompanyShow}
        onOk={addCompanyConfirm}
        onCancel={() => setAddCompanyShow(false)}
        classNames={{ body: "edit_dialog_body" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="dialog_ipt_box dialog_ipt_box_long normal_title">
          <div className="ipt_box_title">
            {t("platform_manager.company_name")}
          </div>
          <Input
            placeholder={t("platform_manager.enter_company")}
            value={addCompanyStr}
            onChange={(e) => setAddCompanyStr(e.target.value)}
          />
        </div>
      </Modal>

      <Modal
        title={t("platform_manager.set_box_type")}
        open={bind_box_type_show}
        onOk={bind_box_type_confirm}
        onCancel={() => setBind_box_type_show(false)}
        classNames={{ body: "edit_dialog_body" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="dialog_ipt_box dialog_ipt_box_long normal_title">
          <div className="ipt_box_title">{t("platform_manager.box")}</div>
          <Select
            placeholder=" "
            mode="multiple"
            value={bind_box_type_name}
            defaultValue={bind_box_type_name}
            options={box_type_list}
            onChange={bind_box_type_change}
          />
        </div>
      </Modal>

      <Modal
        title={t("platform_manager.set_pay_type")}
        open={bind_pay_type_show}
        onOk={bind_pay_type_confirm}
        onCancel={() => setBind_pay_type_show(false)}
        classNames={{ body: "edit_dialog_body" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="dialog_ipt_box dialog_ipt_box_long normal_title">
          <div className="ipt_box_title">{t("platform_manager.pay_type")}</div>
          <Select
            placeholder=" "
            mode="multiple"
            value={bind_pay_type_name}
            defaultValue={bind_pay_type_name}
            options={pay_type_list}
            onChange={bind_pay_type_change}
          />
        </div>
      </Modal>
    </>
  );
}
